<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>admin table</title>
    <link rel="stylesheet" href="../layui/css/layui.css" media="all">
</head>
<body>
<div onclick="openModel('add')" style="margin-left: 2%;margin-top: 10px">
    <button type="button" class="layui-btn">添加分类</button>
</div>
<div class="layui-form" lay-filter="layuiadmin-app-form-list" style="margin: 10px 20px">
    <div>
        <div class="layui-inline">
            <input class="layui-input" id="keywordCate" name="keyword" placeholder="请输入分类名" autocomplete="off">
        </div>
        <button class="layui-btn" id="searchCate" data-type="reload">搜索</button>
    </div>
    <table id="list" lay-filter="list"></table>

</div>
<div id="openAdd" class="layui-row" hidden>
    <div style="margin-left: 10%;margin-top: 20px;width: 80%">
        <form lay-filter="addForm" class="layui-form" action="">
            <input name="id" type="number" hidden/>
            <div class="layui-form-item">
                <label class="layui-form-label">分类名称</label>
                <div class="layui-input-block">
                    <input type="text" name="name" required lay-verify="required" placeholder="请输入分类名称"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">一级分类</label>
                <div class="layui-input-block">
                    <select id="one" lay-filter="one" name="category_id_one" lay-verify="" lay-search>
                        <option data-level="1" value="0">无</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">二级分类</label>
                <div class="layui-input-block">
                    <select id="two" lay-filter="two" name="category_id_two" lay-verify="" lay-search>
                        <option data-level="2" value="0">无</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">分类等级</label>
                <div class="layui-input-block">
                    <input id="levelShow" type="text" lay-verify="" placeholder="系统自动填写"
                           value="一级分类" autocomplete="off" class="layui-input" disabled>
                    <input type="number" id="level" name="level" required lay-verify="required" placeholder="请输入分类名称"
                           value="1" autocomplete="off" class="layui-input" style="display: none">

                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">状态</label>
                <div class="layui-input-block">
                    <input type="radio" name="status" value="1" title="正常" checked>
                    <input type="radio" name="status" value="2" title="禁用">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button id="submit" type="button" class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>

</div>
<div id="openGoodsList" class="layui-row" hidden>
    <div class="layui-form" lay-filter="layuiadmin-app-form-list" style="margin: 10px 20px">
        <div>
            <div class="layui-inline">
                <input class="layui-input" id="keywordGoods" name="keyword" placeholder="请输入商品名" autocomplete="off">
            </div>
            <button class="layui-btn" id="searchGoods" data-type="reload">搜索</button>
        </div>
        <table id="goodsList" lay-filter="goodsList"></table>
        <div style="text-align: center;">
            <button id="bind" type="button" class="layui-btn">立即绑定</button>
        </div>
    </div>
</div>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>

<script src="../layui/layui.js"></script>
<script type="text/html" id="action">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script>

    var tree;
    layui.use('table', function () {
        var table = layui.table;

        //第一个实例
        table.render({
            elem: '#list',
            // height: 312,
            url: 'categoryList?needData=1', //数据接口//
            request: {
                limitName: 'size' //每页数据量的参数名，默认：limit
            },
            parseData: function (res) { //res 即为原始返回的数据
                if (res.code == 200)
                    res.code = 0
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.data //解析数据列表
                };
            },
            page: true,//开启分页
            cols: [[ //表头
                {field: 'id', title: 'ID', width: '100'},
                {field: 'name', title: '分类名称', width: '100'},
                {
                    field: 'level', title: '等级', width: '100', templet: function (d) {
                        var level = '异常'
                        if (d.level == 1)
                            level = '一级分类'
                        if (d.level == 2)
                            level = '二级分类'
                        if (d.level == 3)
                            level = '三级分类'
                        return level;
                    }
                },
                {field: 'category_one_name', title: '一级分类名称', width: '100'},
                {field: 'category_two_name', title: '二级分类名称', width: '100'},
                {
                    field: 'status', title: '销售渠道', width: '100', templet: function (d) {
                        show = '异常'
                        if (d.status == 1)
                            show = '<a class="layui-btn layui-btn-xs" lay-event="disable">启用</a>'
                        if (d.status == 2)
                            show = '<a class="layui-btn layui-btn-xs" lay-event="normal">禁用</a>'
                        return show
                    }
                },
                {field: 'create_time', title: '创建时间', width: '200'},
                {field: 'update_time', title: '更新时间', width: '200'},
                {
                    fixed: 'right', title: '操作', width: '200', templet: function (d) {
                        if (d.level == 3)
                            show = '<a class="layui-btn layui-btn-xs" lay-event="bind">绑定商品</a>\n'
                        else
                            show = ''
                        show = show +
                            '<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>\n' +
                            '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>'
                        return show
                    }
                }
            ]],
            text: {
                none: '暂无数据' //默认：无数据。
            },
            defaultToolbar: ['filter'],

        })
        $('#searchCate').click(function () {
            var keyword = $('#keywordCate').val()
            table.reload('list', {
                url: 'categoryList?needData=1&keyword=' + keyword, //数据接口//
            });

        })

        table.on('tool(list)', function (obj, table) {
            // var data = obj.data; //获得当前行数据
            // if (layEvent == 'edit') {
            //     window.location = 'editPsw.html?aid=' + data.admin_id
            // }
            switch (obj.event) {
                case 'normal':
                    tableSingleAttributeUpdate(obj, 'status', 1)
                    break;
                case 'disable':
                    tableSingleAttributeUpdate(obj, 'status', 2)
                    break;
                case 'bind':
                    openGoodsList( obj)
                    break;
                case 'edit':
                    openModel('edit', obj.data)
                    break;
                case 'del':
                    layer.confirm('确定删除该分类？', function (index) {
                        obj.data['deleted'] = 1
                        edit(obj.data, function (res) {
                            if (res.code != 200) {
                                layer.msg(res.error)
                            } else {
                                layer.msg('修改成功')
                                obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                                layer.close(index);
                            }
                        })
                    });
                    break;

            }
        });

    })
    ;

    function tableSingleAttributeUpdate(obj, field, value) {
        obj.data[field] = value
        edit(obj.data, function (res) {
            if (res.code != 200) {
                layer.msg(res.error)
            } else {
                layer.msg('修改成功')
                var f = {}
                f[field] = value
                obj.update(f);
            }
        })
    }

    function edit(data, callback) {
        $.ajax({
            url: 'editCategory',
            type: 'POST',
            data: data,
            dataType: 'json',
            success: function (res) {
                if (callback != undefined) {
                    callback(res)
                } else {
                    if (res.code != 200) {
                        layer.msg(res.error)
                    } else {
                        layer.msg('修改成功')
                    }
                }
            },
        });
    }

    function openModel(type, data) {
        $.ajax({
            url: 'categoryTree',
            type: 'GET',
            success: function (res) {
                if (res.code != 200) {
                    layer.msg(res.error)
                } else {
                    $('#one').find('option').remove()
                    $("#one").append('<option value="0">无</option>');
                    tree = res.data
                    $.each(res.data, function (index, item) {
                        $("#one").append('<option value="' + item.id + '">' + item.name + '</option>');
                    });
                    if (type == 'add')
                        openAdd()
                    else
                        openEdit(data)

                }
            },
        });
    }

    function openAdd() {
        layer.open({
            type: 1,
            content: $('#openAdd'),
            area: ["500px", "500px"],
            title: '添加分类',
            anim: 1
        });
        $('button[type=reset]').click()
    }

    function openEdit(data) {
        layer.open({
            type: 1,
            content: $('#openAdd'),
            area: ["500px", "500px"],
            title: '编辑分类信息',
            anim: 1,
            success: function () {
                form = layui.form
                var level = '异常'
                if (data.level == 1)
                    level = '一级分类'
                if (data.level == 2)
                    level = '二级分类'
                if (data.level == 3)
                    level = '三级分类'
                $('#levelShow').val(level)
                $('#two').find('option').remove()
                $("#two").append('<option value="0">无</option>');
                $.each(tree, function (index, item) {
                    if (item.id == data.category_id_one) {
                        $.each(item.child, function (k, v) {
                            console.log(v)
                            $("#two").append('<option value="' + v.id + '">' + v.name + '</option>');
                        })
                    }
                })
                form.val('addForm', data)
            }
        });
    }

    //Demo
    layui.use('form', function () {
        var form = layui.form;

        $('#submit').on('click', function () {
            var formData = form.val('addForm')
            if (formData['id'] <= 0)
                delete formData['id']
            else {
                delete formData['file']
                edit(formData, function (res) {
                    if (res.code != 200) {
                        layer.msg(res.error)
                    } else {
                        layer.msg('修改成功')
                        location.reload()
                    }
                })
                return
            }
            $.ajax({
                url: 'addCategory',
                type: 'POST',
                data: formData,
                dataType: 'json',
                success: function (res) {
                    if (res.code != 200) {
                        layer.msg(res.error)
                    } else {
                        layer.msg('添加成功')
                        location.reload();
                    }
                }, error: function (res) {
                    layer.msg()
                }
            })
        })
        form.on('select(one)', function (data) {
            $('#level').val('2')
            $('#levelShow').val('二级分类')
            $('#two').find('option').remove()
            $("#two").append('<option value="0">无</option>');

            $.each(tree, function (index, item) {
                if (item.id == data.value) {
                    console.log(item.child)
                    $.each(item.child, function (k, v) {
                        console.log(v)
                        $("#two").append('<option value="' + v.id + '">' + v.name + '</option>');
                    })
                }
            })
            form.render('select');
        });


        form.on('select(two)', function (data) {
            $('#level').val(3)
            $('#levelShow').val('三级分类')
        });
    });
    function openGoodsList(obj) {
        $('#bind').on('click', function () {
            var data = {}
            data['cateId'] = obj.data['id']
            data['add'] = []
            data['del'] = []
            $('input[name=cateId]').each(function () {
                var status = $(this).prop('checked')
                var v = $(this).val()
                if (status == true) {
                    var rel = {}
                    rel['cate_id'] = data['cateId']
                    rel['goods_id'] = v
                    data['add'].push(rel)
                } else {
                    data['del'].push(v)
                }
            })
            console.log(data)
            $.ajax({
                url: 'editCateRelationship',
                type: 'POST',
                data: data,
                dataType: 'json',
                success: function () {
                    // location.reload()
                }
            })
        })
        $.ajax({
            url: 'cateRelationship?cateId=' + obj.data['id'],
            type: 'GET',
            success: function (relat) {
                var arr = relat.data
                layer.open({
                    type: 1,
                    content: $('#openGoodsList'),
                    area: ["500px", "400px"],
                    title: '商品信息',
                    anim: 1,
                    success: function () {
                        layui.use('table', function () {
                            var table = layui.table;
                            //第一个实例
                            table.render({
                                id: 'goodsList',
                                elem: '#goodsList',
                                height: 300,
                                url: 'goodsList?needData=1&status=1', //数据接口//
                                request: {
                                    limitName: 'size' //每页数据量的参数名，默认：limit
                                },
                                parseData: function (res) { //res 即为原始返回的数据
                                    if (res.code == 200)
                                        res.code = 0
                                    return {
                                        "code": res.code, //解析接口状态
                                        "msg": res.message, //解析提示文本
                                        "count": res.data.total, //解析数据长度
                                        "data": res.data.data //解析数据列表
                                    };
                                },
                                page: true,//开启/分页
                                cols: [[ //表头
                                    {
                                        field: 'id', title: 'ID', width: '100', sort: true, templet: function (d) {
                                            var checked = ''
                                            if ($.inArray(d.id, arr) >= 0)
                                                checked = 'checked'
                                            return '<input value="' + d.id + '" type="checkbox" name="cateId" lay-skin="primary" ' + checked + '><span style="margin-left: 5px">' + d.id + '</span>'
                                        }
                                    },
                                    {field: 'name', title: '商品名称', width: '100'},
                                    {field: 'subtitle', title: '商品副标题', width: '100'},
                                    {
                                        field: 'item', title: '销售渠道', width: '100', templet: function (d) {
                                            show = '异常'
                                            if (d.item == 1)
                                                show = '线上'
                                            if (d.item == 2)
                                                show = '线下'
                                            return show
                                        }
                                    },
                                    {field: 'price', title: '价格', width: '100'},
                                ]],
                            })
                            $('#searchSpe').click(function () {
                                var keyword = $('#keywordSpe').val()
                                table.reload('specificationsList', {
                                    url: 'goodsList?needData=1&status=1&keyword=' + keyword, //数据接口//
                                });
                            })

                        })
                    }
                })
            }
        })
    }
</script>
</body>
</html>
